import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:helloworld/res/goalData.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';

class Goal extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Goal();
  }
}

class _Goal extends State<Goal> with WidgetsBindingObserver {
  Color _itemColor;
  Color _loadColor;
  Color _textColor;
  Color _finishedColor = Colors.blue;
  Color _unFinishColor = Colors.black54;
  Color _boxColor;
  Color _color;
  Color _countColor;
  int flag = 1;
  _getData() async {
    Response response =
        await Dio().get("http://123.207.114.127:1314/goal/selectAll");
    setState(() {
      if (response.data.length == 0) {
        flag = 0;
      } else {
        goalData = response.data;
        //不是第一次加载
        if(isFold.length!=0){
          //添加
          if(isFold.length<goalData.length){
            isFold.insert(0, 1);
            //删除
          }else if(isFold.length>goalData.length){
            isFold.removeAt(goalIndex);
          }
          //第一次加载
        }else {
          for (int i = 0; i < goalData.length; i++) {
            isFold.add(1);
          }
        }
      }
    });
  }

  Future<Null> _refresh() async {
    setState(() {
      flag = 1;
      goalData.clear();
    });
    await _getData();
  }

  Widget _goalItem(int index) {
    if (isFold[index] == 1) {
      return Column(
        children: <Widget>[
          SizedBox(height: 20,),
          Container(
            height: 103,
            width: double.infinity,
            decoration: BoxDecoration(
                color: _itemColor,
                border: Border.all(color: Colors.black12, width: 1),
                borderRadius: BorderRadius.circular(10)),
            padding: EdgeInsets.fromLTRB(35, 0, 0, 0),
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                  // 设置单侧边框的样式
                                    color: Colors.grey,
                                    width: 0.5,
                                    style: BorderStyle.solid))),
                        child:button('${goalData[index]['goalfinish']}', index),
                        height: 40,
                      ),
                      flex: 9,
                    ),
                    Expanded(
                      child: InkWell(
                        child: Container(
                          child: Icon(
                            Icons.navigate_next,
                            size: 30,
                            color: _countColor,
                          ),
                          height: 40,
                          // color: Colors.cyan,
                        ),
                        onTap: () {
                          setState(() {
                            isFold[index] = 0;
                          });
                        },
                      ),
                      flex: 1,
                    )
                  ],
                ),
                Padding(
                  child: Container(
                    height: 40,
                    alignment: Alignment.bottomCenter,
                    decoration: BoxDecoration(
                        border: Border(
                            bottom: BorderSide(
                              // 设置单侧边框的样式
                                color: Colors.grey,
                                width: 0.5,
                                style: BorderStyle.solid))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          '目标内容：',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                        Text(
                          '${goalData[index]['goalcontent']}',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        )
                      ],
                    ),
                  ),
                  padding: EdgeInsets.fromLTRB(0, 0, 35, 0),
                ),
              ],
            ),
          )
        ],
      );
    } else {
      return Column(
        children: <Widget>[
          SizedBox(height: 20,),
          Container(
            height: 180,
            width: double.infinity,
            decoration: BoxDecoration(
                color: _itemColor,
                border: Border.all(color: Colors.black12, width: 1),
                borderRadius: BorderRadius.circular(10)),
            padding: EdgeInsets.fromLTRB(35, 0, 0, 0),
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                  // 设置单侧边框的样式
                                    color: Colors.grey,
                                    width: 0.5,
                                    style: BorderStyle.solid))),
                        child: button('${goalData[index]['goalfinish']}', index),
                        height: 40,
                        // color: Colors.cyan,
                      ),
                      flex: 9,
                    ),
                    Expanded(
                      child: InkWell(
                        child: Container(
                          child: Icon(
                            Icons.keyboard_arrow_down,
                            size: 30,
                            color: _countColor,
                          ),
                          height: 40,
                          // color: Colors.cyan,
                        ),
                        onTap: () {
                          setState(() {
                            isFold[index] = 1;
                          });
                        },
                      ),
                      flex: 1,
                    )
                  ],
                ),
                Padding(
                  child: Container(
                      height: 40,
                      alignment: Alignment.bottomCenter,
                      width: double.infinity,
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                // 设置单侧边框的样式
                                  color: Colors.grey,
                                  width: 0.5,
                                  style: BorderStyle.solid))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            '预计时间：',
                            style: TextStyle(
                              fontSize: 20,
                            ),
                          ),
                          Text(
                            '${goalData[index]['goaltime']}',
                            style: TextStyle(
                              fontSize: 20,
                            ),
                          ),
                        ],
                      )),
                  padding: EdgeInsets.fromLTRB(0, 0, 35, 0),
                ),
                Padding(
                  child: Container(
                    height: 40,
                    alignment: Alignment.bottomCenter,
                    decoration: BoxDecoration(
                        border: Border(
                            bottom: BorderSide(
                              // 设置单侧边框的样式
                                color: Colors.grey,
                                width: 0.5,
                                style: BorderStyle.solid))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          '目标内容：',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                        Text(
                          '${goalData[index]['goalcontent']}',
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        )
                      ],
                    ),
                  ),
                  padding: EdgeInsets.fromLTRB(0, 0, 35, 0),
                ),
                Padding(
                  child: Container(
                      height: 40,
                      alignment: Alignment.bottomCenter,
                      width: double.infinity,
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                // 设置单侧边框的样式
                                  color: Colors.grey,
                                  width: 0.5,
                                  style: BorderStyle.solid))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            '宣言：',
                            style: TextStyle(
                              fontSize: 20,
                            ),
                          ),
                          Text(
                            '${goalData[index]['goaloath']}',
                            style: TextStyle(
                              fontSize: 20,
                            ),
                          ),
                        ],
                      )),
                  padding: EdgeInsets.fromLTRB(0, 0, 35, 0),
                ),
              ],
            ),
          )
        ],
      );
    }
  }

  Widget _loadData() {
    if (goalData.length == 0 && flag == 1) {
      return Container(
          child: Center(
        child: Loading(
            indicator: BallPulseIndicator(), size: 100.0, color: _loadColor),
      ));
    } else if (goalData.length == 0 && flag == 0) {
      return Container(
          child: Center(
        child: ListView(
          children: <Widget>[
            SizedBox(
              height: 200,
            ),
            Center(
              child: Text(
                '暂无目标信息',
                style: TextStyle(color: _textColor, fontSize: 30),
              ),
            )
          ],
        ),
      ));
    } else {
      return ListView(
          children: goalData.asMap().keys.map((f) {
        return InkWell(
          child: _goalItem(f),
          onTap: () {
            Navigator.pushNamed(context, '/goalDetail',
                arguments: {'index': f});
          },
        );
      }).toList());
    }
  }

  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if (window.platformBrightness == Brightness.dark) {
      _itemColor = Colors.black12;
      _color = Colors.black45;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _countColor = Colors.white;
      _boxColor = Colors.grey;
      _finishedColor = Colors.greenAccent;
      _unFinishColor = Colors.white54;
    } else {
      _itemColor = Colors.black12;
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _countColor = Colors.black54;
      _boxColor = Colors.black26;
      _finishedColor = Colors.blue;
      _unFinishColor = Colors.black54;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    if (window.platformBrightness == Brightness.dark) {
      _itemColor = Colors.black12;
      _color = Colors.black45;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _countColor = Colors.white;
      _boxColor = Colors.grey;
      _finishedColor = Colors.greenAccent;
      _unFinishColor = Colors.white54;
    } else {
      _itemColor = Colors.black12;
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _countColor = Colors.black54;
      _boxColor = Colors.black26;
      _finishedColor = Colors.blue;
      _unFinishColor = Colors.black54;
    }
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
          width: double.infinity,
          decoration: BoxDecoration(color: _color,
              // gradient: LinearGradient(
              //   begin: Alignment.centerLeft,
              //   end: Alignment.centerRight,
              //   colors: [Colors.lightBlueAccent, Colors.deepPurpleAccent],
              // ),
            border: Border(
                bottom: BorderSide(
                  // 设置单侧边框的样式
                    color: Colors.grey,
                    width: 0.1,
                    style: BorderStyle.solid))
          ),
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  decoration: BoxDecoration(
                    // color: Colors.lightGreen,
                    borderRadius: BorderRadius.circular(10),
//                  border: Border.all(color: Colors.black12,width: 1),
                  ),
                  height: 50,
                  width: 130,
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "已完成：",
                          style: TextStyle(fontSize: 20, color: _textColor),
                        ),
                        finished()
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(width: 10,),
              Expanded(
                child: Container(
                  height: 25,
                  width: 1,
                  decoration:
                      BoxDecoration(border: Border.all(color: _boxColor)),
                ),
                flex: 0,
              ),
              SizedBox(width: 10,),
              Expanded(
                flex: 1,
                child: Container(
                  height: 50,
                  width: 130,
                  decoration: BoxDecoration(
                    // color: Colors.redAccent,
                    borderRadius: BorderRadius.circular(10),
//                  border: Border.all(color: Colors.black12,width: 1),
                  ),
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "未完成：",
                          style: TextStyle(fontSize: 20, color: _textColor),
                        ),
                        unfinish()
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(width: 10,),
              Expanded(
                child: Container(
                  height: 25,
                  width: 1,
                  decoration:
                      BoxDecoration(border: Border.all(color: _boxColor)),
                ),
                flex: 0,
              ),
              Expanded(
                flex: 1,
                child: InkWell(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.edit,
                        size: 25,
                        color: _countColor,
                      ),
                      Text(
                        "立下目标",
                        style: TextStyle(
                          fontSize: 10,
                        ),
                      )
                    ],
                  ),
                  onTap: () {
                    Navigator.pushNamed(context, '/addGoal');
                  },
                ),
              )
            ],
          ),
        ),
        // SizedBox(
        //   height: 10,
        // ),
        Expanded(
          child: Container(
            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            child: RefreshIndicator(
              child: _loadData(),
              displacement: 20,
              onRefresh: _refresh,
            ),
          ),
        )
      ],
    );
  }

  Widget button(String yesOrNo, int index) {
    if (yesOrNo == 'yes') {
      return FlatButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        // color: _finishedColor,
        child:
            Text('已完成', style: TextStyle(fontSize: 22, color: _finishedColor)),
        onPressed: () {
          setState(() {
            goalData[index]['goalfinish'] = 'no';
          });
          Dio().post("http://123.207.114.127:1314/goal/updateGoal",
              queryParameters: {
                'goalid': goalData[index]['goalid'],
                'goaltime': goalData[index]['goaltime'],
                'goalcontent': goalData[index]['goalcontent'],
                'goaloath': goalData[index]['goaloath'],
                'goalfinish': 'no'
              });
        },
      );
    } else {
      return FlatButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        // color: _unFinishColor,
        child:
            Text('未完成', style: TextStyle(fontSize: 22, color: _unFinishColor)),
        onPressed: () {
          setState(() {
            goalData[index]['goalfinish'] = 'yes';
          });
          Dio().post("http://123.207.114.127:1314/goal/updateGoal",
              queryParameters: {
                'goalid': goalData[index]['goalid'],
                'goaltime': goalData[index]['goaltime'],
                'goalcontent': goalData[index]['goalcontent'],
                'goaloath': goalData[index]['goaloath'],
                'goalfinish': 'yes'
              });
        },
      );
    }
  }

  Widget finished() {
    int total = 0;
    for (int i = 0; i < goalData.length; i++) {
      if (goalData[i]['goalfinish'] == 'yes') {
        total++;
      }
    }
    return Text(
      "${total}",
      style: TextStyle(fontSize: 30, color: _countColor),
    );
  }

  Widget unfinish() {
    int total = 0;
    for (int i = 0; i < goalData.length; i++) {
      if (goalData[i]['goalfinish'] == 'no') {
        total++;
      }
    }
    return Text(
      "${total}",
      style: TextStyle(fontSize: 30, color: _countColor),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}
